<?php
/**
 * Created by PhpStorm.
 * User: 47557
 * Date: 2017/4/13
 * Time: 14:06
 */

namespace app\db\controller;


use think\Db;
use think\Exception;

class Plancontrol extends Dbcommoncontrol
{
    protected $DbName="PlanInf";

    /**
     * 根据计划id得到计划
     * @return string
     */
    public function  GetPlan()
    {
        try {
            $id = $_POST["p_id"];
            if ($id != null) {
                $plan = Db::table($this->DbName)->where('P_Id', '=', $id)->find();
                if ($plan == null)
                    return "no plan";
                else
                    return json_encode($plan);
            }
        }
        catch (Exception $ex)
        {
            return $ex->getMessage();
        }
    }
    public function Add()
    {
        try
        {
            $rd=parent::array_to_object(json_decode($_POST["rd"],true));//获取转数组转对象;
            Db::startTrans();
            //其他计划变为不是主要
            $this->otherfalse($rd->U_Id);
            //添加
            $record=$this->Getnew();//获取当前控制器对应的模型的对象
            $record->data($rd);//给对象填充数据
            $record->save();//保存
            $id=DB::table($this->DbName)->where('P_isRead','=',"true")
                ->where("U_Id",'=',$rd->U_Id)->find()["P_Id"];
                return $id;

        }
        catch (Exception $ex)
        {
            Db::rollback();
            return $ex->getMessage();
        }

       // return parent::Add(); // TODO: Change the autogenerated stub
    }
    public function UserALert()
    {
        try {
            $rd = parent::array_to_object(json_decode($_POST["rd"], true));//获取转数组转对象;
            Db::startTrans();
            //其他计划变为不是主要
            $this->otherfalse($rd->U_Id);
            $sql=$this->Getnew()->update($rd);
            return "true";
        }
        catch (Exception $ex){
            Db::rollback();
            return $ex->getMessage();
        }
    }
    protected  function otherfalse($u_id)
    {
        //其他计划变为不是主要

        $other=DB::table($this->DbName)->where("U_Id",'=',$u_id)->select();
        foreach ($other as $i)
        {
            $i["P_IsRead"]="false";
            $this->Getnew()->update(parent::array_to_object($i));
        }


    }
}